package token.mobileapp.controlactivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import token.mobileapp.R;
import token.mobileapp.TokenActivity;
import token.mobileapp.model.UserInfo;
import token.mobileapp.persistenceactivity.UserInfoPersistence;
import token.mobileapp.utils.Constants;
import token.mobileapp.utils.NetworkUtils;

import java.io.IOException;

/**
 * token.mobileapp.controlactivity
 * Author: AVAVT
 * Date: 8/8/11
 * Time: 12:39 AM
 */
public class ChangeSecretKey extends TokenActivity implements View.OnClickListener{
    private Button buttonBack, buttonApply;
    private AlertDialog alertDialog = null;
    private EditText etSecretKey;

    UserInfo userInfo = null;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_secret_key);
        buttonBack = (Button) findViewById(R.id.secret_btn_back);
        buttonBack.setOnClickListener(this);

        buttonApply = (Button) findViewById(R.id.secret_btn_apply);
        buttonApply.setOnClickListener(this);

        etSecretKey = (EditText) findViewById(R.id.secret_et_secretKey);

        Intent intent = new Intent(this, UserInfoPersistence.class);
        startActivityForResult(intent, Constants.REQUEST_CODE_LOAD_USER);
    }

    public void onClick(View view) {
        if (view.getId() == R.id.secret_btn_back) {
            finish();
        } else if (view.getId() == R.id.secret_btn_apply) {
            if(etSecretKey.getText().toString().compareTo("") == 0){
                displayAlert("Please enter new secret key.");
            }
            else if(etSecretKey.getText().toString().length() != 6){
                displayAlert("Secret key must be a 6-digits number.");
            }
            else{
                buttonApply.setClickable(false);
                userInfo.setSecretKey(etSecretKey.getText().toString());
                attach();
            }
        }
    }

    private void attach(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Contacting server...")
                .setCancelable(false);
        alertDialog = builder.create();
        alertDialog.show();

        if (userInfo != null) {
            try {
                if(NetworkUtils.changeSecret(userInfo.getSeed(), userInfo.getSecretKey())){
                    Intent intent = new Intent(this, UserInfoPersistence.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("userInfo", userInfo);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constants.REQUEST_CODE_SAVE_USER);
                }
                else{
                    alertDialog.dismiss();
                    displayAlert("A problem occurred while performing request. Please try again.");
                }

            } catch (IOException e) {
                alertDialog.dismiss();
                displayAlert("A problem occurred while trying to communicate with server. Please make sure you are connected to the internet and try again.");
            }
        } else {
            alertDialog.dismiss();
            displayAlert("A problem occurred while performing request. Please try again.");

            Intent loadIntent = new Intent(this, UserInfoPersistence.class);
            startActivityForResult(loadIntent, Constants.REQUEST_CODE_LOAD_USER);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_CODE_LOAD_USER && resultCode == Activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            userInfo = (UserInfo) bundle.getSerializable("userInfo");
        }
        else if (requestCode == Constants.REQUEST_CODE_LOAD_USER && resultCode == Activity.RESULT_CANCELED) {
            displayError(data);
        }
        else if (requestCode == Constants.REQUEST_CODE_SAVE_USER && resultCode == Activity.RESULT_OK) {
            buttonApply.setClickable(true);

            if(alertDialog != null && alertDialog.isShowing()){
                alertDialog.dismiss();
            }

            displayAlertThenFinish("Secret key changed successfully.");
        }
        else if (requestCode == Constants.REQUEST_CODE_SAVE_USER && resultCode == Activity.RESULT_CANCELED) {
            if(alertDialog != null && alertDialog.isShowing()){
                alertDialog.dismiss();
            }
            displayError(data);
            buttonApply.setClickable(true);
        }
    }
}
